/*
 * 监控区主页的主区域, 概况
 * 命名空间 "general"
 * 
 * @author Zdream
 * @since 0.2.0
 */

monitor.ui.body.addContent({
	name : "general",
	
	state : {
		
	},
	
	init : function () {
		this.state = {
			screens : []
		};
		
		this.refreshScreenInfo();
		
		// monitor.store
		// vm create
		this.vm = new Vue({
			el: "#mnt_body",
			data: this.state
		});
		
		// 消息监听
		var thiz = this;
		monitor.msgCenter.subscribe(
				["aside-add-button", "aside-remove-button", "aside-refresh-button", "status-change",
					"query-data-project"],
		function(event, argv) {
			switch (event) {
			case "aside-add-button":
			case "aside-remove-button":
			case "aside-refresh-button":
			{
				thiz.onRefreshButton();
			} break;
			case "status-change": {
				thiz.onStatusChange(argv);
			} break;
			case "query-data-project": {
				thiz.handleQueryProject(argv);
			} break;
			}
		}, this.name);
	},
	
	onRefreshButton : function () {
		this.refreshScreenInfo();
	},
	
	/**
	 * 当服务器告诉监控区, 展示屏的状态发生了变化
	 */
	onStatusChange : function (data) {
		// data.sid
		// data.pid
		// data.status
		var screens = this.state.screens;
		var length = screens.length;
		
		for (var i = 0; i < length; i++) {
			var s = screens[i];
			
			if (s.sid == data.sid) {
				s.status = data.status;
				var pid = data.pid;
				s.pid = s.pname = pid;
				
				if (pid != null) {
					var project = monitor.store.queryProject(pid);
					if (project != null) {
						s.pname = project.name;
					}
				}
				break;
			}
		}
	},
	
	refreshScreenInfo : function () {
		var screens = this.state.screens;
		screens.splice(0, screens.length); // 清空
		
		var source = monitor.store.screens;
		var index = 0;
		for (var sid in source) {
			var pid = source[sid].pid, pname = pid;
			
			if (pid != null) {
				var project = monitor.store.queryProject(pid);
				if (project != null) {
					pname = project.name;
				}
			}
			
			this.state.screens.push({
				sid : sid,
				status : source[sid].status, // 可能为 null
				pid : source[sid].pid, // 可能为 null
				pname : pname,
				connect : source[sid].connect
			});
		}
	},
	
	handleQueryProject : function (data) {
		var pid = data.pid;
		var pname = data.name;
		
		var dirt = false;
		var length = this.state.screens.length;
		for (var i = 0; i < length; i++) {
			var screen = this.state.screens[i];
			if (screen.pid == pid) {
				screen.pname = pname;
				dirt = true;
			}
		}
		
		if (dirt) {
			this.vm.$forceUpdate();
		}
	},
	
	destroy : function () {
		this.state = null;
		
		// 删除消息监听
		monitor.msgCenter.remove(this.name);
		
		// vm destroy
		this.vm.$destroy();
		this.vm = null;
		
	}
	
});
